// JavaScript Document

	function brkUnixToDate(u){
		var d = new Date();
		d.setTime(u*1000);
		d = d.toUTCString();
		return d.replace(/\d\d:/, '<br />' + /\d\d:/.exec(d));	
	}
	
	var View = {
		cur:0,
		views:['view_cont','view_meta','view_arb'],
		alter:function(a, b){
			a.split(',').each(function(id){ $(id).style.display = (b) ? 'block' : 'none'; });
		},
		switchTo:function(a){ 
			this.cur = a;
			for(i=0; i<3; i++) this.alter(this.views[i], (i == a));
			this.switched(a);
		},
		switched:function(a){}
	}

	var File = {
		load:function(o){
			for(var k in o) this[k] = o[k];
			this.write = this.perms[1];
			this.setreadonly(!this.write);
			for(var k in {title:'', description:'', tags:''}) $(k).value = this[k];
			Arb.clear();
			for(var k in this.meta) Arb.set(k, this.meta[k]);
			body.setCode(this.body);
			$('file_updated').innerHTML = brkUnixToDate(this.updated);
			if(this.id == O_ID) $('filesize').innerHTML = bytesize(this.filesize);
			if($('usurpbtn')) $('usurpbtn').value = (this.id != O_ID && this.id == USURPA) ? 'Unusurp!' : 'Usurp!';
			if($('tmpl')) $('tmpl').style.display = (this.template) ? 'block' : 'none';
			if(this.template) $('tmplfmrp').innerHTML = this.template.fmrp
			if($('lnkbtn')) $('lnkbtn').value = (this.template) ? 'Detach' : 'Attach';
			Drafts.cache(this);
			this.loaded();
		},
		loaded:function(){
			
		},
		setreadonly:function(b){
			if(!b) b = false
			$('save').disabled = body.textarea.readOnly = $('title').readOnly = $('description').readOnly = $('tags').readOnly = b;
			body.setReadOnly(b);
			$('readonly').style.display = (b) ? 'block' : 'none';
		},
		// Saving
		args:{},
		gatherArgs:function(){
			this.args = {id:this.id, fmrp:this.fmrp}
			var set = {}
			for(var k in {title:'', description:'', tags:''}) set[k] = $(k).value;
			set.body = body.getCode().trim();
			set.meta = Arb.gather();
			this.args.set = set;
			this.gathered();
		},
		gathered:function(){
			
		},
		callAjax:function(f){
			var s = ajaxExec(f, this.args);
			this.args = {};
			return s;
		},
		// Functions
		save: function(){
			if(!this.write) return
			this.gatherArgs();
			return this.callAjax('saveFile');
		},
		saveAs:function(){
			Browser.load({task:'savefile', title:'Copy ' + this.fmrp + ' to:', btntxt:'save', input:File.basename, onselect:function(){
				if(!Browser.inp.value) return;
				File.saveTo(Browser.location, Browser.inp.value);																					   
			}});
			Browser.goto('/');
		},
		saveTo:function(path, basename, victim){
			this.gatherArgs();
			this.args.set.basename = basename;
			if(victim) this.args.victim = victim;
			Smajax.exec('saveTo', this.args, path);
			this.args = {};
		},
		newDraft:function(){
			if(!this.write) return;
			this.gatherArgs();
			this.args.id = O_ID;
			this.args.cur = this.id;
			return this.callAjax('newDraft');
		},
		overwrite:function(){
			if(!this.write) return;
			this.gatherArgs();
			this.args.id = O_ID;
			this.args.draft_id = this.id;
			return this.callAjax('overwrite');
		},
		usurp:function(){
			if(this.id == O_ID) return;
			this.gatherArgs();
			this.args.usurpa = (this.id == USURPA) ? '' : this.id;
			return this.callAjax('usurp');
		},
		linkTemplate:function(){
			if(this.template){
				this.gatherArgs();
				this.args.set.template = '';
				return this.callAjax('saveFile');
			}
			Browser.load({task:'link', title:'Link template to ' + File.basename, input:(File.template ? File.template.fmrp : ''), btntxt:'link', onselect:function(){
				if(!Browser.inp.value) return;
				File.doLink(Browser.inp.value);															   
			}});
			Browser.goto('/');
		},
		doLink:function(id){
			if(!this.write) return
			this.gatherArgs();
			this.args.set.template = id;
			this.callAjax('saveFile');
			Browser.hide()
		},
		showInfo:function(){
			SideOps.def()	
		}
	}

	var Drafts = {
		_CACHE:{},
		load:function(o){
			this.index = {};
			this.length = 0;
			for(var k in o){
				this.index[k] = o[k];
				this.length++;
			}
			this.draw();
			//$('hasdrafts').style.display = (this.length) ? 'block' : 'none';
		},
		clear:function(){
			this._CACHE = {}
			this.load({});
		},
		draw:function(){
			var items = {}, str = '', i = 0;
			items[O_ID] = 'Original File';
			for(var id in this.index) items[id] = this.index[id];
			for(var id in items){
				str += '<div style="padding-bottom:4px; text-align:right">';
				if(id == File.id){
					$('draftno').innerHTML = (id == O_ID) ? 'Original File' : 'Draft #' + i + ' of ' + this.length;
					str += '<strong ' + (id == USURPA ? 'class="usurpa" ' : '') +'><span style="float:left">-></span> ';
					$('usrpbull').style.display = (id == USURPA) ? 'block' : 'none';
				}else{
					str += '<a ' + (id == USURPA ? 'class="usurpa" ' : '') + 'href="javascript:Drafts.switchTo(\'' + id + '\')">';
				}
				str += ((id == O_ID) ? 'Original File' : brkUnixToDate(items[id])) + ((id == File.id) ? '</strong></div>' : '</a></div>');
				i++;
			}
			$('draftslist').innerHTML = str;
			$('hasdrafts').style.display = (File.id == O_ID) ? 'none' : 'block';
		},
		switchTo:function(id){
			//$('bigwait').show();
			if(this._CACHE[id]){
				File.load(this._CACHE[id]);
				this.draw();
				return;
			}
			File.args = {id:id}
			File.callAjax('switchDraft');
		},
		discard:function(all){
			File.args = {id:O_ID}
			File.args.draft_id = (all) ? '' : File.id;
			TUXconfirm('Sure?', function(a){
				if(a) File.callAjax('unDraft');
			});
		},
		cache:function(o){
			c = {}
			for(var k in o) if(typeof o[k] != 'function') c[k] = o[k];
			this._CACHE[c.id] = c;
		}
	}
	
	var Arb = {
		arbs:function(){
			return $A(document.getElementsByClassName('arb'));
		},
		set:function(k, v){
			this.clean();
			var a = this.arbs();
			for(i=0; i<a.length; i++){
				var x = $('arbk'+i).value;
				if(!x) break;
				if(x == k) return $('arbv'+i).value = v;
			}
			var y = i+1;
			this.mk(y);
			$('arbk'+y).value = k;
			$('arbv'+y).value = v;
			this.clean();
		},
		gather:function(){
			this.clean();
			var o = {};
			for(i=0; i<this.arbs().length; i++) if($('arbk'+i).value) o[$('arbk'+i).value] = $('arbv'+i).value;
			return o;
		},
		clear:function(){
			var n = this.arbs().length;
			for(i=0; i<n; i++) $('arbk'+i).value = '';
			this.clean();
		},
		clean:function(){
			var a = this.arbs();
			var n = 0;
			for(i=0; i<a.length; i++){
				var k = $('arbk'+i).value = $('arbk'+i).value.trim();
				if(k){
					n = i;
					continue;
				}
				if(a[i+1]){
					k = $('arbk'+i).value = $('arbk'+(i+1)).value;
					if(k) n = i;
					$('arbv'+i).value = $('arbv'+(i+1)).value;
					$('arbk'+(i+1)).value = $('arbv'+(i+1)).value = '';
					continue;
				}
				if(i) $('arb'+i).style.opacity = 0;
			}
			this.mk(n+1);
		},
		mk:function(y){
			if($('arb'+y)) return $('arb'+y).style.opacity = 1;
			var tr = $('arb').appendChild(mk('tr', {
				id:'arb'+y,
				className:'arb'
			}));
			var tdk = tr.appendChild(mk('td'));
			var tdv = tr.appendChild(mk('td'));
			var inp = tdk.appendChild(mk('input', {
				id:'arbk'+y,
				type:'text',
				className:'arbk'
			}));
			inp.style.width = '100px';
			Event.observe(inp, 'change', Arb.clean.bind(Arb));
			var inpv = tdv.appendChild(mk('input', {
				id:'arbv'+y,
				type:'text',
				className:'arbv'
			}));
			inpv.style.width = '400px';
			this.clean();
		}
	}
	
	var AutoSave = function(periodical){
		if(!File.write) return;
		addEvent(document, 'keydown', keyEvents.cmdSave);
		if(!Object.isUndefined(periodical) && !periodical) return;
		var as = ($C('fmgrAutoSave').value || 0);
		$('as_mins').value = as;
		$('as_chk').checked = (as) ? 'checked' : false;
		
		$('as_chk').toggle = function(){
			var chk = (this.checked) ? true : false;
			$('as_inp').style.opacity = (chk) ? 1 : 0.2;
			$('as_mins').disabled = !chk;
			$('as_mins').setTimer(chk);
		}
		
		$('as_mins').check = function(hold){
			this.value = (parseInt(this.value) || 0);
			if(this.value == 0) $('as_chk').checked = false;
			$('as_chk').toggle();
		}
		
		$('as_mins').setTimer = function(go){
			$C('fmgrAutoSave').value =  this.value;
			$C('fmgrAutoSave').expires = 0;
			$C('fmgrAutoSave').path = '/';
			$C('fmgrAutoSave').write();
			clearInterval(this.interval);
			if(!go || this.value == 0) return;
			this.interval = setInterval(function(){
				// We can always disable the checkbox if we want to suspend autosaving
				if($('as_chk').disabled) return;
				File.save();
				$('as_chk').toggle();
			}, this.value*60*1000);
		}
		
		addEvent($('as_chk'), 'change', $('as_chk').toggle);
		addEvent($('as_mins'), 'change', $('as_mins').check);
		
		$('as_chk').checked = false;
		$('as_mins').check();
	}
	
	var keyEvents = {
		tabs:function(e){
			if(e.keyCode != 9) return;
			var s = (!e.shiftKey) ? '\t' +  keyEvents.selection(e).replace(/\n/gm, "\n\t") : keyEvents.selection(e).replace(/\n\t/gm, "\n");
			Event.stop(e)
			keyEvents.insert(e, s);
			return;
		},
		boldetc:function(e){
			if(!keyEvents.cmdTest(e)) return;
			var s = keyEvents.selection(e);
			//if(e.keyCode != 91) alert(e.keyCode);
			switch(e.keyCode){
				// shift+s
				case 83:
					if(!e.shiftKey) return;
					s = '<span>' + s + '</span>';
					break;
				// shift+g
				case(71):
					if(!e.shiftKey) return;
					s = '<strong>' + s + '</strong>';
					break;
				// shift+e
				case(69):
					if(!e.shiftKey) return;
					s = '<em>' + s + '</em>';
					break;
				// shift+d
				case(68):
					if(!e.shiftKey) return;
					s = '<div>' + s + '</div>';
					break;
				// cmd+rtn (br)
				case(Event.KEY_RETURN):
					if(s) return;
					s = '<br />\n';
					break;
				default:	
					return;
			}
			Event.stop(e)
			keyEvents.insert(e, s);
		},
		cmdSave:function(e){
			if(!keyEvents.cmdTest(e)) return;
			switch(e.keyCode){
				// s
				case 83:
					if(e.shiftKey) return;
					Event.stop(e)
					window.parent.window.File.save();
					return;
				// n
				case 78:
					if(!e.shiftKey) return;
					Event.stop(e)
					window.parent.window.File.newDraft();
					return;
				// u
				case 85:
					if(!e.shiftKey) return;
					Event.stop(e)
					window.parent.window.File.usurp();
					return;
			}
		},
		cmdTest:function(e){
			return (window.isapple) ? e.metaKey : e.ctrlKey;
		},
		selection:function(e){
			// appends '' since safari returns an object which of course doesn't equate to false even though it may only contain an empty string
			return (e.view.document.getSelection ? e.view.document.getSelection() : e.view.window.getSelection()) + ''
		},
		insert:function(e, s){
			e.view.window.CodePress.insertCode(s); 
		}
	}
	
	var cp_onload = function(w){
		w.isapple = (window.navigator.userAgent.indexOf('Macintosh') > -1);
		addEvent(w.document, 'keydown', keyEvents.tabs);
		addEvent(w.document, 'keydown', keyEvents.boldetc);
		addEvent(w.document, 'keydown', keyEvents.cmdSave);
		addEvent(w.document, 'keydown', function(e){
			if(!keyEvents.cmdTest(e) || e.keyCode != 90) return;
			Event.stop(e)
			e.shiftKey ? w.CodePress.actions.redo() : w.CodePress.actions.undo();
		});
		Event.observe(w.document, 'click', SideOps.def);
	}
	
	var SideOps = {
		collapsers : Array,
		init : function() {
			SideOps.collapsers = $A(document.getElementsByClassName('collapser'));
			SideOps.collapsers.each(function(collapser){
				Event.observe(collapser, 'click', SideOps.collapse);
				Element.cleanWhitespace(collapser.parentNode);
			});
			var i = 0;
			var int = setInterval(function(){
				SideOps.dodef();
				i++;
				if(i < 2) return
				clearInterval(int)
				Smernel.fire('SideOps:loaded')
			}, 750)			
		},
		dodef:function(){
			SideOps.collapse({originalTarget:SideOps.collapsers[0]});
		},
		def:function(e){
			if(!Element.hasClassName(SideOps.collapsers[0].nextSibling, 'closed')) return;
			SideOps.dodef()
		},
		getEventSrc : function (e) {
			if (!e) e = window.event;
			if (e.originalTarget)
				return e.originalTarget;
			else if (e.srcElement)
			return e.srcElement;
		},
		done:function(){
			SideOps.intransition = false
		},
		collapse : function(e) {
			if(SideOps.intransition) return
			SideOps.intransition = true
			var tl = SideOps.getEventSrc(e).nextSibling;
			SideOps.collapsers.each(function(el){
				el = el.nextSibling;
				var closed = Element.hasClassName(el,'closed');
			if (el == tl && closed ) {
				new Effect.Parallel(
					[
						new Effect.SlideDown(el,{sync:true}),
						new Effect.Appear(el,{sync:true})
					],
					{
						duration:0.7,
						fps:40,
						afterFinish:SideOps.done
					}
				);
				Element.removeClassName(el,'closed');
			} else if(!closed) {
				new Effect.Parallel(
					[
						new Effect.SlideUp(el,{sync:true}),
						new Effect.Fade(el,{sync:true})
					],
					{
						duration:0.7,
						fps:40,
						afterFinish:SideOps.done
					}
				);
				Element.addClassName(el,'closed')
			}
			});
		}
	};
	window.queue(SideOps.init);
	Smernel.observe('SideOps:loaded', function(){ Event.observe($('maincell'), 'click', File.showInfo, false) });
